// 引入vue
import Vue from 'vue'
// 引入 vue-router
import VueRouter from 'vue-router'
// 引入 routes
import routes from './routes.js'
// 引入仓库
import store from '@/store'

// 重写VueRouter 的push, replace方法，保存原始push, replace方法
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

// 用call 是因为originPush，是绑定到vm身上的，所以要改变上下文，用call
// 为什木不用bind ？ 因为 bind传参是数组
// VueRouter.prototype.push = function (location, resolve, reject) {
//   if (resolve && reject) {
//     originPush.call(this, location)
//   }else {
//     originPush.call(this, location, ()=>{}, ()=>{})
//   }
// }
// VueRouter.prototype.replace = function (location, resolve, reject) {
//   if (resolve && reject) {
//     originReplace.call(this, location)
//   } else {
//     originReplace.call(this, location, ()=>{}, ()=>{})
//   }
// }
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject) return originPush.call(this, location, resolve, reject)
  return originPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function push(location, resolve, reject) {
  if (resolve || reject) return originReplace.call(this, location, resolve, reject)
  return originPush.call(this, location).catch(err => err)
}

// 注册vue-router
Vue.use(VueRouter)


const router =  new VueRouter({
  routes,
  scrollBehavior () {
    return { y: 0 }
  }
})

router.beforeEach((to, from, next)=>{
  let token = store.state.loginAndRegister.token
  let name = store.state.loginAndRegistter ? store.state.loginAndRegistter.userInfo.name : ''
  // console.log(store.state.loginAndRegistter);
  // console.log(token);
  // to 去哪
  // from 从哪来
  // next 跳转函数  next('路径'), next() 放行  , next(false) 中断
  // 是否登陆
  if (token) {
    // 如果有  跳转为 login 
    console.log('有token');
    if (to.path === '/login' ||  to.path === '/register') {
      console.log('登陆了跳转为login');
      next({name: 'home'})
    }else{
      // 如果登陆了  并且不是去 login 放行
      //  放行前 如果仓库有数据
      console.log('登陆了跳转为其他');
      if (name) {
        console.log('有name');
        next()
      }else{
        // 如果没数据 去请求
        console.log('无数据');
        store.dispatch('loginAndRegister/getUserInfo').then(res=>{
          console.log(res);
        }).catch(()=>{
          // 如果出现失败 说明token 失效 需要重新 删除失效token 登陆获取 touken
          // 删除token
          store.dispatch('loginAndRegister/loginOut').then(()=>{
            next({name: 'login'})
          }).catch((err)=> {
            console.log(err);
          })
        })
        next()
      }
    }
  }else{
    console.log('无touken');
    // 如果跳 订单 trade 购物车 shopcart 个人中心 center 支付  pay paysuccess 则需要跳转登陆
    let toPath = to.path
    console.log(toPath);
    if (toPath === '/trade' || toPath === '/shopcart' || toPath.indexOf('/center') !== -1  || toPath === '/pay' || toPath === '/paysuccess') {
      next('/login?redirect='+ toPath)
    }
    next()
  }
  
})



// 默认暴露
export default router